package com.star.wellconnect.profile;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.star.wellconnect.BaseActivity;
import com.star.wellconnect.R;
import com.star.wellconnect.WellConnectActivity;
import com.star.wellconnect.sqlite.AppPreferences;
import com.star.wellconnect.sqlite.Patient;

public class ProfileActivity extends BaseActivity{
	private static final int GALLERY = 1;
    private ImageView mProfilePic;
    private Patient mPatient;
	private Bitmap bitmap = null;
    
	public ProfileActivity() {
		super(R.string.app_name);
	}
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_profile);
		
		mPatient = AppPreferences.getPatient(this);
		
		mProfilePic = (ImageView)findViewById(R.id.profile_pic);
		mProfilePic.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				intent.addCategory(Intent.CATEGORY_OPENABLE);
				startActivityForResult(intent, GALLERY);
			}
		});
		
		if(mPatient.image != null)
			mProfilePic.setImageBitmap(BitmapFactory.decodeByteArray(mPatient.image, 0, mPatient.image.length));
		
		final EditText username = (EditText) findViewById(R.id.username);
		username.setText(mPatient.username);
		final EditText password = (EditText) findViewById(R.id.password);
		password.setText(AppPreferences.getPatientPassword(this));
		final EditText name = (EditText) findViewById(R.id.name);
		name.setText(mPatient.name);
		final EditText email = (EditText) findViewById(R.id.email);
		email.setText(mPatient.email);
		final EditText phone = (EditText) findViewById(R.id.phone);
		phone.setText(mPatient.phone);
		final TextView error = (TextView) findViewById(R.id.error);
		Button update = (Button) findViewById(R.id.update);
		
		// Listener
		TextWatcher inputFieldsValidatorTextWatcher = new TextWatcher(){
			@Override
			public void afterTextChanged(Editable arg0) {}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				error.setText("");
			}
		};

		username.addTextChangedListener(inputFieldsValidatorTextWatcher);
		password.addTextChangedListener(inputFieldsValidatorTextWatcher);
		name.addTextChangedListener(inputFieldsValidatorTextWatcher);
		phone.addTextChangedListener(inputFieldsValidatorTextWatcher);
		email.addTextChangedListener(inputFieldsValidatorTextWatcher);

		update.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(isNotEmpty()){
					if(isUnchanged()){
						error.setText("No fields has been modified");
					}else{
						ByteArrayOutputStream stream = new ByteArrayOutputStream();
						bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
						byte[] newImg = stream.toByteArray();
						
						Patient patient = new Patient(username.getText().toString().trim(),
								"0",
								name.getText().toString().trim(),
								email.getText().toString().trim(),
								phone.getText().toString().trim(),
								newImg);
						
						if(AppPreferences.updatePatient(getApplication(), patient) >= 0
								&& AppPreferences.updatePatientPassword(getApplication(), 
										password.getText().toString().trim()) >= 0){
			                Intent intent = new Intent(v.getContext(), WellConnectActivity.class);
			                startActivity(intent);
						}else{
							error.setText("An error occurred. Please try again later.");
						}
					}
				}else{
					error.setText("Please fill out all fields.");
				}
			}
			
			private boolean isNotEmpty(){
				return username.getText().toString().trim().length() > 0
						&& password.getText().toString().trim().length() > 0
						&& email.getText().toString().trim().length() > 0
						&& phone.getText().toString().trim().length() > 0
						&& name.getText().toString().trim().length() > 0;
			}
			
			private boolean isUnchanged(){
				return username.getText().toString().trim().equals(mPatient.username)
						&& password.getText().toString().trim().equals(AppPreferences.getPatientPassword(getApplication()))
						&& email.getText().toString().trim().equals(mPatient.email)
						&& phone.getText().toString().trim().equals(mPatient.phone)
						&& name.getText().toString().trim().equals(mPatient.name);
			}
		});
		
		getActionBar().setDisplayHomeAsUpEnabled(false);
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == GALLERY && resultCode == Activity.RESULT_OK && data != null){
			try{
				if(bitmap != null){
					bitmap.recycle();
				}
				InputStream inputStream = getContentResolver().
						openInputStream(data.getData());
				
				bitmap = BitmapFactory.decodeStream(inputStream);
				inputStream.close();
				mProfilePic.setImageBitmap(bitmap);
				
				// Save to database
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
				mPatient.image = outputStream.toByteArray();
				AppPreferences.updatePatient(this, mPatient);
			}catch(FileNotFoundException e){
				Log.e("FileNotFoundException", e.getMessage());
			}catch(IOException e){
				Log.e("IOException", e.getMessage());
			}
			super.onActivityResult(requestCode, resultCode, data);
		}
	}
	
	public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
}
